﻿public bool ReadResponseAsString { get; set; }

protected virtual async System.Threading.Tasks.Task<ObjectResponseResult<T>> ReadObjectResponseAsync<T>(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers)
{
    if (response == null || response.Content == null)
    {
        return new ObjectResponseResult<T>(default(T), string.Empty);
    }

    if (ReadResponseAsString)
    {
        var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        try
        {
            var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseText, {% if UseRequestAndResponseSerializationSettings %}Response{% endif %}JsonSerializerSettings);
            return new ObjectResponseResult<T>(typedBody, responseText);
        }
        catch (Newtonsoft.Json.JsonException exception)
        {
            var message = "Could not deserialize the response body string as " + typeof(T).FullName + ".";
            throw new {{ ExceptionClass }}(message, (int)response.StatusCode, responseText, headers, exception);
        }
    }
    else
    {
        try
        {
            using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
            using (var streamReader = new System.IO.StreamReader(responseStream))
            using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader))
            {
                var serializer = Newtonsoft.Json.JsonSerializer.Create({% if UseRequestAndResponseSerializationSettings %}Response{% endif %}JsonSerializerSettings);
                var typedBody = serializer.Deserialize<T>(jsonTextReader);
                return new ObjectResponseResult<T>(typedBody, string.Empty);
            }
        }
        catch (Newtonsoft.Json.JsonException exception)
        {
            var message = "Could not deserialize the response body stream as " + typeof(T).FullName + ".";
            throw new {{ ExceptionClass }}(message, (int)response.StatusCode, string.Empty, headers, exception);
        }
    }
}